import {_decorator, Component, EventTouch, Input, input, Node, tween, UITransform, Vec2, Vec3} from 'cc';
import {GridSystemManage} from "db://assets/script/modules/GridSystemManage";
import {GameManager} from "db://assets/script/modules/GameManager";

const {ccclass, property} = _decorator;

@ccclass('JoystickController')
export class JoystickController extends Component {

    playerNode: Node = null;
    gameCameraNode: Node = null;
    joystickBox: Node = null;
    joystickCenter: Node = null;

    gridSize: number = 64; // 新增格子尺寸参数
    private _moveDir: Vec2 = new Vec2(0, 0);    // 当前移动方向
    private _isTouchStart: boolean = false
    private _isTouchMove: boolean = false;      // 是否正在移动
    private _targetPosition: Vec3 = new Vec3();  // 新增目标位置
    private _isPlayerMoving: boolean = false;    // 移动状态锁

    start() {
        this.gridSize = GridSystemManage.gridSize
        this.playerNode = GameManager.playerNode
        this.gameCameraNode = GameManager.gameCameraNode
        this.joystickBox = this.node.getChildByName('JoystickBox')
        this.joystickCenter = this.joystickBox.getChildByName('JoystickCenter');

        // 初始化触摸事件监听
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    update(deltaTime: number) {
        this.playerControl();
    }

    onDestroy() {
        // 初始化触摸事件监听
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
        input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    // 触摸开始回调
    onTouchStart(event: EventTouch) {
        const touchPos = event.getUILocation();
        const uiTransform = this.joystickBox.parent.getComponent(UITransform);
        const localPos = uiTransform.convertToNodeSpaceAR(new Vec3(touchPos.x, touchPos.y, 0));

        // 确保触摸位置在Joystick范围内
        const joystickBoxContentSize = this.joystickBox.getComponent(UITransform).contentSize;
        const contentSize = this.getComponent(UITransform).contentSize;
        const minX = joystickBoxContentSize.width / 2
        const minY = joystickBoxContentSize.height / 2
        const maxX = contentSize.width - joystickBoxContentSize.width / 2
        const maxY = contentSize.height - joystickBoxContentSize.height / 2
        if (localPos.x > maxX || localPos.y > maxY || localPos.x < minX || localPos.y < minY) {
            return
        }

        this._isTouchStart = true
        this.joystickBox.setPosition(localPos.x, localPos.y)
    }

    // 触摸移动回调
    onTouchMove(event: EventTouch) {
        if (!this._isTouchStart) {
            return
        }
        // 获取触摸点UI坐标
        const touchUIPos = event.getUILocation();
        // 转换为摇杆box节点的本地坐标
        const uiTransform = this.joystickBox.parent.getComponent(UITransform);
        const localTouchPos = uiTransform.convertToNodeSpaceAR(new Vec3(touchUIPos.x, touchUIPos.y, 0));
        // 计算相对于box中心的偏移向量
        const boxPos = this.joystickBox.position;
        const offset = new Vec2(localTouchPos.x - boxPos.x, localTouchPos.y - boxPos.y);

        // 限制移动半径
        const maxRadius = this.joystickBox.getComponent(UITransform).contentSize.width / 2;
        const distance = offset.length();
        const minRadius = 20
        if (distance < minRadius) {
            this._moveDir.set(Vec2.ZERO); // 停止移动
            this.joystickCenter.setPosition(Vec3.ZERO); // 摇杆归中
            this._isTouchMove = false;
            return;
        }
        if (distance > maxRadius) {
            offset.multiplyScalar(maxRadius / distance); // 向量缩放
        }

        // 更新摇杆中心位置
        this.joystickCenter.setPosition(offset.x, offset.y);

        // 传递方向给玩家控制
        const rawDirection = offset.clone().normalize();
        // 判断轴向锁定（水平或垂直）
        const absX = Math.abs(rawDirection.x);
        const absY = Math.abs(rawDirection.y);
        const threshold = 0.2;

        if (absX > absY + threshold) {
            this._moveDir.set(Math.sign(rawDirection.x), 0); // 水平方向
        } else if (absY > absX + threshold) {
            this._moveDir.set(0, Math.sign(rawDirection.y)); // 垂直方向
        }

        this._isTouchMove = true;
    }

    // 触摸结束回调
    onTouchEnd() {
        const uit = this.getComponent(UITransform)
        this._isTouchStart = false
        this.joystickBox.setPosition(uit.contentSize.width / 2, uit.contentSize.height / 2); // 回归原点
        this.joystickCenter.setPosition(Vec3.ZERO); // 回归原点
        this._moveDir.set(0, 0); // 停止移动
        this._isTouchMove = false;
    }

    private playerControl() {
        if (!this._isTouchMove || this._isPlayerMoving) return;

        // 计算目标网格位置
        this._targetPosition = this.playerNode.position.clone().add(new Vec3(this._moveDir.x * this.gridSize, this._moveDir.y * this.gridSize, 0));

        // 检查目标位置是否无法通行
        const grid = GridSystemManage.nodePosToGridPos(this._targetPosition)
        if (GridSystemManage.checkTargetIsMargin(grid)) {
            // console.log('到头边缘了')
            return;
        }
        if (GridSystemManage.checkTargetIsNoCross(grid)) {
            // console.log('到头了')
            return;
        }

        // 启动格子移动
        this._isPlayerMoving = true;

        // 使用tween实现平滑移动
        tween(this.playerNode)
            .to(0.2, {position: this._targetPosition}, {
                easing: 'linear',
                onUpdate: () => {
                    this.gameCameraNode.setPosition(this.playerNode.position)
                },
                onComplete: () => {
                    // 强制对齐网格中心
                    this.playerNode.setPosition(this._targetPosition);
                    this._isPlayerMoving = false;
                }
            })
            .start();
    }
}


